<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;

class Api extends Controller
{
    public function __construct(Request $request)
    {
        $this->data = $request->param();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
    }

    //获取对应的地区信息
    public function getprovinces(Request $request)
    {
        $data = $request->param();
        $tables = $data['tables'];//表名
        $did = $data['id'];//查询的id
        $map = array();
        if ($request->isPost()) {
            switch ($tables) {
                case 'provinces'://省份
                    $map['country_id'] = array('in', $did);
                    break;
                case 'city'://城市
                    $map['province_id'] = array('in', $did);
                    break;
                case 'town'://地区
                    $map['city_id'] = array('in', $did);
                    break;
                case 'street'://街道
                    $map['town_id'] = array('in', $did);
                    break;
                default:
                    $map = array();
                    break;
            }
            $data = Db::name($tables)->where($map)->select();
            return json_encode($data);
        }
    }

    //通过公司类型获取类型下的公司属性 以及业务员
    public function getcoattr(Request $request)
    {
        $admin=session('admin');
        $resdata = $request->param();
        $cotype = $resdata['cotype'];//分类名称
        //匹配公司类型属性
        $where['b.cotype_ids'] = array('like', '%' . $cotype . '%');
        $where['b.person'] = 0;//使用公司的属性
        //获取分类名称
        $where['a.lang'] = $resdata['lang'];//语言标志
        if ($resdata['country_id']) {
            //通用和自己国家
            $where['b.country_id'] = array('in', ['0', $resdata['country_id']]);
        }
        $join = [
            ['nt_coattr b', 'a.mkey=b.mkey']
        ];
        $table = 'multi_lang';
        $coarr = getmultidata($table, $join, $where)['data'];//属性信息
        //获取对应的属性中值，select,text
        foreach ($coarr as $cokey => $covalue) {
            if ($covalue['is_text'] == 1) {
                //select框
                $datacoattr = Db::name('coattr_select')->where('coattr_id', $covalue['id'])->select();
                foreach ($datacoattr as $datacoattrkey => $datacoattrval) {
                    $coarr[$cokey]['textselect'][] = array('content' => $datacoattrval['option_text'], 'id' => $datacoattrval['id']);
                }
            } else if ($covalue['is_text'] == 0) {
                //文本框
                $coarr[$cokey]['textselect'][] = array();
            }
        }
        //子级是不可以选择父级员工  (全球管理员1 CEO 2)
        if($cotype==1 || $cotype==3){
            //供应商 配件厂（中国总经理4，采购经理60，采购员63）中
            if($resdata['country_id']){
                if($resdata['country_id']==1){
                    //巴西
                    $posionids=array('1','2');
                }elseif ($resdata['country_id']==2){
                    //中国
                    $posionids=array('1','2','4','60','63');
                }
            }else{
                //没有国家限制
                $posionids=array('1','2','4','60','63');
            }
            if($admin['position_id']==2){
                $posionids=array_diff($posionids, ['1']);
            }
            if($admin['position_id']==4){
                $posionids=array_diff($posionids, ['1','2']);
            }
            if($admin['position_id']==60){
                $posionids=array_diff($posionids, ['1','2','4']);
            }
            if($admin['position_id']==63){
                $posionids=array_diff($posionids, ['1','2','4','60']);
            }
            $posstr['position_id']=array('in',implode(',',$posionids));
            $posstr['status']=1;
            $managename=getables('admin',$posstr,'id,nickname');
        }
        if($cotype==2){
            //经销商（巴西总经理3，市场总监5，客户经理10，销售主管11，业务组长13 高级业务员14，业务员15，实习业务员16） 巴西
            if($resdata['country_id']){
                if($resdata['country_id']==1){
                    //巴西
                    $posionids=array('1','2','3','5','10','11','13','14','15','16');
                }elseif ($resdata['country_id']==2){
                    //中国
                    $posionids=array('1','2');
                }
            }else{
                //没有国家限制
                $posionids=array('1','2','3','5','10','11','13','14','15','16');
            }
            if($admin['position_id']==2){
                $posionids=array_diff($posionids, ['1']);
            }
            if($admin['position_id']==3){
                $posionids=array_diff($posionids, ['1','2']);
            }
            if($admin['position_id']==5){
                $posionids=array_diff($posionids, ['1','2','3']);
            }
            if($admin['position_id']==10){
                $posionids=array_diff($posionids, ['1','2','3','5']);
            }
            if($admin['position_id']==11){
                $posionids=array_diff($posionids, ['1','2','3','5','10']);
            }
            if($admin['position_id']==13){
                $posionids=array_diff($posionids, ['1','2','3','5','10','11']);
            }
            if($admin['position_id']==14){
                $posionids=array_diff($posionids, ['1','2','3','5','10','11','13']);
            }
            if($admin['position_id']==15){
                $posionids=array_diff($posionids, ['1','2','3','5','10','11','13','14']);
            }
            if($admin['position_id']==16){
                $posionids=array_diff($posionids, ['1','2','3','5','10','11','13','14','15']);
            }
            $posstr['position_id']=array('in',implode(',',$posionids));
            $posstr['status']=1;
            $managename=getables('admin',$posstr,'id,nickname');
        }
        if($cotype==4){
            //货贷（巴西总经理3 中国总经理4 ） 中巴
            if($resdata['country_id']){
                if($resdata['country_id']==1){
                    //巴西
                    $posionids=array('1','2','3');
                }elseif ($resdata['country_id']==2){
                    //中国
                    $posionids=array('1','2','4');
                }
            }else{
                //没有国家限制
                $posionids=array('1','2','3','4');
            }
            if($admin['position_id']==2){
                $posionids=array_diff($posionids, ['1']);
            }
            if($admin['position_id']==3 || $admin['position_id']==4){
                $posionids=array_diff($posionids, ['1','2']);
            }
            $posstr['position_id']=array('in',implode(',',$posionids));
            $posstr['status']=1;
            $managename=getables('admin',$posstr,'id,nickname');
        }
        if($cotype==5){
            //物流（巴西总经理3，运维总监7，物流管理员30 中国总经理4 ）巴（3,7,30） 中（4）
            if($resdata['country_id']){
                if($resdata['country_id']==1){
                    //巴西
                    $posionids=array('1','2','3','7','30');
                }elseif ($resdata['country_id']==2){
                    //中国
                    $posionids=array('1','2','4');
                }
            }else{
                //没有国家限制
                $posionids=array('1','2','3','4','7','30');
            }
            if($admin['position_id']==2){
                $posionids=array_diff($posionids, ['1']);
            }
            if($admin['position_id']==3 || $admin['position_id']==4){
                $posionids=array_diff($posionids, ['1','2']);
            }
            if($admin['position_id']==7){
                $posionids=array_diff($posionids, ['1','2','3']);
            }
            if($admin['position_id']==30){
                $posionids=array_diff($posionids, ['1','2','7','3']);
            }
            $posstr['position_id']=array('in',implode(',',$posionids));
            $posstr['status']=1;
            $managename=getables('admin',$posstr,'id,nickname');
        }
        if(!$cotype){
            $coarr=$managename=array();
        }
        echo json_encode(array('coattr'=>$coarr,'managename'=>$managename));
    }

    //处理语言
    public function lang()
    {
        return is_lang($_GET['lang_type']);
    }

    //获取对应国家的省份
    public function getpro(Request $request)
    {
        $res = $request->param();
        $table = $res['table'];
        $proid = $res['pro_id'];
        switch ($table) {
            case 'provinces':
                //获取对应国家的省份
                if (!$proid) {
                    $data = Db:: name($table)->select();
                } else {
                    $data = Db:: name($table)->where('country_id', $proid)->select();
                }
                break;
            case 'city':
                //获取对应省份的城市
                if (!$proid) {
                    $data = Db:: name($table)->select();
                } else {
                    $data = Db:: name($table)->where('province_id', $proid)->select();
                }
                break;
            case 'town':
                //获取城市下的城镇
                if (!$proid) {
                    $data = Db:: name($table)->select();
                } else {
                    $data = Db:: name($table)->where('city_id', $proid)->select();
                }
                break;
            case 'admin':
                $data = Db:: name($table)->field('id,nickname')->where('position_id', $proid)->select();
                break;
        }
        echo json_encode($data);
    }

    //获取对应国家下的职务和对应国家下的部门
    public function postionfrmaes(Request $request)
    {
        $data = $request->param();
        if ($request->isPost() && $request->isAjax()) {
            $table = $data['table'];
            $lang = $data['lang'];
            $country_id = $data['country_id'];
            $datares = getFrames($table, $lang, $country_id);
            echo json_encode($datares);
        }
    }


    // 根据公司ID(company_id)，获取采购合同信息
    public function getBuyPo(Request $request)
    {
        $data = $request->param();
        if (isset($data['company_id']) && $data['company_id']) $where['zu.company_id'] = $data['company_id'];
        if (isset($data['po_ids']) && $data['po_ids']) $where['zu.id'] = ['in', $data['po_ids']];
        $where['zu.finish_day'] = isset($data['finish_day']) && $data['finish_day'] > 0 ? $data['finish_day'] : 0;
        $where['zu.sign_day'] = ['>', 0];

        $buyPoList = model('Buy')->getBuyPo($where, is_lang(), ['zu.id,zu.delivery_day,zu.paid_sum,zu.price_sum,zu.cost_sum']);
        $returnData = [];
        if (!empty($buyPoList)) $returnData = model('Buy')->getPaypoarr($buyPoList, 'add');
        foreach ($returnData as $k => $v) {
            if (empty($v['cost_list'])) unset($returnData[$k]['cost_list']);
        }
        // dump($returnData);die;
        echo json_encode($returnData);
    }


    // 根据合同ID 获取详情
    public function getBuyPoInfo(Request $request)
    {
        $data = $request->param();
        if (!isset($data['po_id']) && empty($data['po_id'])) return json_encode(array('code' => 500, 'msg' => lang('please_select_a_contract')));
        $where['zu.id'] = $data['po_id'];
        $returnData = model('Buy')->getBuyPo($where, is_lang());
        if (!empty($returnData)) {
            foreach ($returnData as $k => $v) {
                $returnData[$k]['status_name'] = $v['sign_day'] > 0 ? '已签约' : '';
                $returnData[$k]['status_name'] = $v['receipt_day'] > 0 ? '已收货' : $returnData[$k]['status_name'];
                $returnData[$k]['status_name'] = $v['finish_day'] > 0 ? '已完成' : $returnData[$k]['status_name'];
                $returnData[$k]['status_name'] = $returnData[$k]['status_name'] ? $returnData[$k]['status_name'] : '准备中';
                $terms = getDatas('buy_po_terms', ['*'], ['po_id' => $v['id']]);
                if (!empty($terms)) {
                    foreach ($terms as $k1 => $v1) {
                        $returnData[$k]['terms'][$v1['type']]['id'] = $v1['id'];
                        $returnData[$k]['terms'][$v1['type']]['content'] = $v1['content'];
                    }
                }

                $buy_po_logs = getDatas('buy_po_logs', ['*'], ['po_id' => $v['id']]);
                if (!empty($buy_po_logs)) {
                    foreach ($buy_po_logs as $k2 => $v2) {
                        $returnData[$k]['buy_po_logs'][$k2]['content'] = $v2['content'];
                        $returnData[$k]['buy_po_logs'][$k2]['happen_at'] = getTimeDates($v2['happen_at'], is_lang());
                        $returnData[$k]['buy_po_logs'][$k2]['admin_name'] = $v2['admin_id'] == '' ? '-' : getinfo($v2['admin_id'], 'admin')['nickname'];//编辑者
                    }
                }
                $buypoarr = getDatas('buy_po_pay', ['*'], ['po_id' => $v['id']],'pay_day asc');
                $returnData[$k]['buypoarr_amount'] = 0;
                if (!empty($buypoarr)) {
                    foreach ($buypoarr as $k3 => $v3) {
                        $returnData[$k]['buypoarr'][$k3]['amount'] = $v3['amount'];
                        $returnData[$k]['buypoarr'][$k3]['pay_day'] = getTimeDate($v3['pay_day'],7);
                        $returnData[$k]['buypoarr'][$k3]['percent'] = $v3['percent'];
                        $returnData[$k]['buypoarr_amount'] += $v3['amount'];
                    }
                }

                // 获取其他费用代支付信息
                $cost_list = getDatas('buy_po_cost', ['*'], ['po_id' => $v['id']]);
                $returnData[$k]['cost_amount'] = 0;
                if (!empty($cost_list)) {
                    foreach ($cost_list as $k4 => $v4) {
                        $returnData[$k]['cost_list'][$k4]['amount'] = $v4['amount'];
                        $returnData[$k]['cost_list'][$k4]['remarks'] = $v4['remarks'];
                        $returnData[$k]['cost_list'][$k4]['is_apportion'] = $v4['apportion'] == 1 ? 'O' : '-'; // 分摊
                        $returnData[$k]['cost_list'][$k4]['replace_pay'] = $v4['is_replace_pay'] == 1 ? 'O' : '-'; //代付
                        $returnData[$k]['cost_amount'] += $v4['amount'];
                    }
                }

                // h获取支付流水信息
                $join = [['fin_co2buy f', 'zu.fin_co2buy_id = f.id'], ['accounts a', 'f.account_id = a.id']];
                $fin_co2buy_po = getSearch('fin_co2buy_po', 'zu', ['zu.*,f.happen_day,f.create_id,a.bankname,a.account_name,a.account_num'], ['po_id' => $v['id']], $join, 'zu.id desc');
                $returnData[$k]['fin_co2buy_po_amount'] = 0;
                if (!empty($fin_co2buy_po)) {
                    foreach ($fin_co2buy_po as $k5 => $v5) {
                        $returnData[$k]['fin_co2buy_po'][$k5] = $v5;
                        $returnData[$k]['fin_co2buy_po'][$k5]['happen_day'] = explode(' ', getTimeDates($v5['happen_day'], is_lang()))[0];
                        $returnData[$k]['fin_co2buy_po'][$k5]['create_name'] = $v5['create_id'] == '' ? '-' : getinfo($v5['create_id'], 'admin')['nickname'];//编辑者
                        $returnData[$k]['fin_co2buy_po_amount'] += $v5['amount'];
                    }
                }
                // 获取收款账号信息
                $join1 = [['fin_co2buy f', 'zu.fin_co2buy_id = f.id'], ['banks b', 'f.bank_id = b.id'], ['co_bank cb', 'b.id = cb.banks_id']];
                $content_sum = getSearch('fin_co2buy_po', 'zu', ['b.name,cb.bankname,cb.account_name,cb.account_num'], ['po_id' => $v['id']], $join1, 'zu.id desc');
                if (!empty($content_sum)) {
                    $returnData[$k]['content_sum'] = $content_sum[0];
                } else {
                    $returnData[$k]['content_sum']['name'] = '';
                    $returnData[$k]['content_sum']['bankname'] = '';
                    $returnData[$k]['content_sum']['account_name'] = '';
                    $returnData[$k]['content_sum']['account_num'] = '';
                }

                $returnData[$k]['plan_sum'] = count($returnData[$k]['buy_plan']);
                $returnData[$k]['weifu_sum'] = $returnData[$k]['buypoarr_amount'] + $returnData[$k]['cost_amount'] - $returnData[$k]['fin_co2buy_po_amount'];
            }
        }
        echo json_encode($returnData[0]);
    }


    // 获取 付款登记 采购应付款项
    public function getBuyPo_pain(Request $request)
    {
        $data = $request->param();
        $delivery_at_start = isset($data['date']['year']) && isset($data['date']['month']) ? mktime(0, 0, 0, date($data['date']['month']), 1, date($data['date']['year'])) : strtotime(date('Y-m-01'));
        $delivery_at_end = isset($data['date']['year']) && isset($data['date']['month']) ? mktime(23, 59, 59, date($data['date']['month']), date('t'), date($data['date']['year'])) : mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        $where['zu.finish_day'] = 0;
        $where['zu.sign_day'] = ['>', 0];
        
        // 获取一级部门下的采购合同
        if( session('admin')['position_id'] != 1 && session('admin')['position_id'] != 2){

            $admin_country_id = getValue('department',['id'=>session('admin')['department_id']],'country_id');
            if($admin_country_id == 2){
                $departmentPid = 3;
            }else if($admin_country_id == 1){
                $departmentPid = 2;
            }
            $department_ids = implode(',', array_column( getInfiniteSort('department', null, $admin_country_id,$departmentPid), 'id')); 
            $department_ids .= $department_ids ? ','.$departmentPid : $departmentPid;

            // 获取一级部门的所有相关人员
            $admin_ids = implode(',', array_column(  getDatas('admin',['id'],['department_id'=>['in',$department_ids]]),'id'));

            // 设置获取合同条件
            $where['zu.create_id'] = ['in',$admin_ids];
        }
        

        $ids = getDatas('buy_po_pay', ['po_id'], ['pay_day' => ['between', $delivery_at_start . ',' . $delivery_at_end]]);
        if (!empty($ids)) $where['zu.id'] = ['in', implode(array_column($ids, 'po_id'), ',')];
        $buyPoList = model('Buy')->getBuyPo($where, is_lang(), ['zu.id,zu.company_id,zu.delivery_day,zu.paid_sum,zu.price_sum,zu.cost_sum']);
        // dump($buyPoList);die;
        $returnData = [];
        $returnDatass = [];
        $size = 0;
        $returnDatass['page']['page'] = 1;
        if (!empty($buyPoList)) {
            $returnData = model('Buy')->getPaypoarr($buyPoList, '', true, $data['date']['year'] . '-' . $data['date']['month'] . '-01');
            if (!empty($returnData)) {
                $price_sum = 0;
                foreach ($returnData as $k => $v) {
                    // if ($v['cost_list']['amount'] == 0) unset($v['cost_list']);
                    $returnDatas[$v['company_name']][] = $v;
                }
            }
            $size = count($returnDatas);
            // 获取分页数据
            if (isset($data['page']) && isset($data['limit'])) {
                $returnDatass['list'] = array_slice($returnDatas, $data['limit'] * ($data['page'] - 1), $data['limit']);
                $returnDatass['page']['page'] = $data['page'];
            } else {
                $returnDatass['list'] = $returnDatas;
                $returnDatass['page']['page'] = 1;
            }
        }
        $returnDatass['page']['size'] = $size;
        // dump($returnDatass);die;
        echo json_encode($returnDatass);
    }

    // 根据流水ID获取该流水下公司的合同，获取当前流水合同ID及之后的合同信息
    public function getBuyPoAndCompany(Request $request)
    {
        $data = $request->param();
        if (!isset($data['fin_co2buy_id']) && !empty($data['fin_co2buy_id'])) return json_encode(array('code' => 500, 'msg' => '请选择正确的财务流水'));
        if (!isset($data['company_id']) && !empty($data['company_id'])) return json_encode(array('code' => 500, 'msg' => '请选择正确的财务流水'));
        $po_ids = getGroup('fin_co2buy_po', ['po_id'], ['fin_co2buy_id' => $data['fin_co2buy_id']], 'po_id');
        if (!empty($po_ids)) {
            $po_ids = array_column($po_ids, 'po_id');
            $po_idstr = implode(',', $po_ids);
        }
        $where['zu.finish_day'] = 0;
        $whereOr['zu.id'] = ['in', $po_idstr];
        $buyPoList = model('Buy')->getBuyPo($where, is_lang(), ['zu.id,zu.delivery_day,zu.paid_sum,zu.price_sum,zu.cost_sum'], $whereOr);
        $returnData = [];
        if (!empty($buyPoList)) $returnData = model('Buy')->getPaypoarr($buyPoList);
        foreach ($returnData as $k => $v) {
            if (!empty($v['paypoarr'])) {
                foreach ($v['paypoarr'] as $k1 => $v1) {
                    // 获取当前流水ID下，付款安排被支付的数额
                    $fin_co2buy_amount = getValue('fin_co2buy_po', ['buy_po_payId' => $v1['id'], 'fin_co2buy_id' => $data['fin_co2buy_id']], 'amount');
                    $fin_co2buy_amount = $fin_co2buy_amount ? $fin_co2buy_amount : 0;
                    // 获取当前支付安排已经支付得历史流水(当前支付流水不在内)
                    $amount_sum = Db::name('fin_co2buy_po')->where(['buy_po_payId' => $v1['id'], 'fin_co2buy_id' => ['not in', $data['fin_co2buy_id']]])->sum('amount');
                    $has = hasData('fin_co2buy_po', ['fin_co2buy_id' => $data['fin_co2buy_id'], 'buy_po_payId' => $v1['id']]);
                    if ($v1['amount'] - $amount_sum == 0 && !$has) {
                        unset($returnData[$k]['paypoarr'][$k1]);
                    } else {
                        $returnData[$k]['paypoarr'][$k1]['price'] = $fin_co2buy_amount;
                        $returnData[$k]['paypoarr'][$k1]['amount'] = $v1['amount'] - $amount_sum;
                        $returnData[$k]['paypoarr'][$k1]['paid'] = $v1['paid'] - $fin_co2buy_amount;
                    }

                }
            }
            if (!empty($v['cost_list'])) {
                // 获取当前流水ID下，其他费用代付的被支付的数额
                $fin_co2buy_costamount = getValue('fin_co2buy_po', ['buy_po_payId' => 0, 'fin_co2buy_id' => $data['fin_co2buy_id'], 'po_id' => $v['id']], 'amount');
                // 获取当前其他费用代父款已经支付得历史流水(当前支付流水不在内)
                $costamount_sum = Db::name('fin_co2buy_po')->where(['buy_po_payId' => 0, 'fin_co2buy_id' => ['not in', $data['fin_co2buy_id']], 'po_id' => $v['id']])->sum('amount');
                $has_cost = hasData('fin_co2buy_po', ['fin_co2buy_id' => $data['fin_co2buy_id'], 'buy_po_payId' => 0, 'po_id' => $v['id']]);

                if ($returnData[$k]['cost_list']['amount'] - $costamount_sum == 0 && !$has_cost) {
                    unset($returnData[$k]['cost_list']);
                } else {
                    $returnData[$k]['cost_list']['price'] = $fin_co2buy_costamount;
                    $returnData[$k]['cost_list']['amount'] = $returnData[$k]['cost_list']['amount'] - $costamount_sum;
                    $returnData[$k]['cost_list']['paid'] = $returnData[$k]['cost_list']['paid'] - $fin_co2buy_costamount;
                }
            }
        }
        // dump($returnData);die;
        echo json_encode($returnData);
    }

    //日记账的保存请求接口
    public function journaladdedit(Request $request)
    {
        $data = $request->param();
        $journal = new \app\admin\model\Journal();
        if ($request->isPost() && $request->isAjax()) {
            $journalret = $journal->journaladdedit($data);
            $udata["status"] = $journalret['status'];
            $udata['msg'] = $journalret['msg'];
            echo json_encode($udata);
        }
    }

    //处理对excel的处理
    public function tlend()
    {
        require('PHPExcel/PHPExcel/IOFactory.php');
        //选取读取的文件
        $filename = 'lend.xlsx';
        $objPHPExcel = \PHPExcel_IOFactory::load($filename);//全部加载文件
        /*
         * 读取sheet中的内容1
         */
        $sheetCount = $objPHPExcel->getSheetCount();//读取excel文件有多少个sheet
        for ($i = 0; $i < $sheetCount; $i++) {
            $data = $objPHPExcel->getSheet($i)->toArray();//读取每一个sheet里面的数据，全部放到数组中
        }
        unset($data[0]);
        $resdatazh = array();
        $resdataen = array();
        $resdatapt = array();
        //去掉重复的内容
        $resdatazh = array();
        foreach ($data as $datakey => $dataval) {
            if ($dataval[1]) {
                if (!in_array($dataval[1], $resdatazh)) {
                    array_push($resdatazh, $dataval[1]);
                    array_push($resdataen, $dataval[2]);
                    array_push($resdatapt, $dataval[3]);
                }
            }
        }
        $arrone = array();
        $arrtwo = array();
        $arrthree = array();
        //中文
        foreach ($resdatazh as $resdatazhkey => $resdatazhval) {
            $abbreviation = str_replace(' ', '_', $resdataen[$resdatazhkey]);
            $arrone[] = array('lang' => 'zh', 'content' => $resdatazhval, 'abbreviation' => $abbreviation);
        }
        //英文
        foreach ($resdataen as $resdataenkey => $resdataenval) {
            $abbreviation = str_replace(' ', '_', $resdataenval);
            $arrtwo[] = array('lang' => 'en', 'content' => $resdataenval, 'abbreviation' => $abbreviation);
        }
        //葡文
        foreach ($resdatapt as $resdataptkey => $resdataptval) {
            $abbreviation = str_replace(' ', '_', $resdataen[$resdataptkey]);
            $arrthree[] = array('lang' => 'pt', 'content' => $resdataptval, 'abbreviation' => $abbreviation);
        }

//         $res = Db::name('dict')->where(['id'=>['>','339']])->delete();

        //写入数据
//        Db::name('dict')->insertAll($arrone);
//        Db::name('dict')->insertAll($arrtwo);
//        Db::name('dict')->insertAll($arrthree);

        dump($arrone);
        die;
//        dump($arrtwo);
        //dump($arrthree);
    }

    public function export_file()
    {
        $data = Db::name('dict')->select();
        $name = 'dict_' . date("Y-m-d", time());
        $this->push($data, $name);
        // $this->redirect('export');
    }

    public function getProcharCodebar()
    {
        $codebar = $this->verificationCodebar();
        return $codebar;
    }

    //复制时原职位名称
    public function getcopypostion(Request $request)
    {
        $data = $request->param();
        $posits = getpostion('position', $data['id']);//当前职位的父级id
        $positarr = array();
        foreach ($posits as $positkey => $positval) {
            $poids = 'position_' . $positval;
            array_unshift($positarr, $poids);
        }
        $mapwhere['mkey'] = ['in', $positarr];
        //获取对应的职位名称
        return getlangname('multi_lang', $mapwhere, $data['lang']);
    }

    //获取公司的名称
    public function getcompanyname(Request $request)
    {
        if ($request->isAjax() && $request->isPost()) {
            $companyname = '';
            $data = $request->param();
            if (isset($data['company_id'])) {
                $companyname = getinfo($data['company_id'], 'company')['name'];//公司名称
            }
            return $companyname;
        }
    }

    function verificationCodebar()
    {
        $codebarPrefix = '78997187';
        $rand = rand(1, 9999);
        switch (strlen($rand)) {
            case '1':
                $codebar = $codebarPrefix . '000' . $rand;
                break;
            case '2':
                $codebar = $codebarPrefix . '00' . $rand;
                break;
            case '3':
                $codebar = $codebarPrefix . '0' . $rand;
                break;
            case '4':
                $codebar = $codebarPrefix . $rand;
                break;
        }

        $has = hasData('prochar', ['codebar' => $codebar]);
        if ($has) {
            $codebar = $this->verificationCodebar();
        }
        return $codebar;
    }

    function getLangType()
    {
        $langData = Db::name('language')->field(['name', 'code'])->where('status', '1')->select();
        if ($langData[0]['code'] != $this->lang) {
            $checkLangData = [];
            foreach ($langData as $keylangData => $valuelangData) {
                if ($valuelangData['code'] == $this->lang) {
                    $checkLangData['name'] = $valuelangData['name'];
                    $checkLangData['code'] = $this->lang;
                    unset($langData[$keylangData]);
                }
            }
            array_unshift($langData, $checkLangData);
        }
        return json_encode($langData);
    }
    //测试facebook 的登录
    function index(){

        return view('index/facebook');
    }
    function facebook(Request $request){
        $res=$request->param();
        if($request->isGet()){
            //验证
            dump(cookie('adminfacebook'));
        }else if($request->isAjax() && $request->isPost()){
            //验证用户登陆接口
            $url='https://graph.facebook.com/debug_token?access_token=4324794930896522%7Cc309f939fca79f889eb2ccf3d8218ef7&input_token='.$res['idToken'];
            $data=json_decode(file_get_contents($url),true);
            if($data['data']['is_valid']){
                cookie('adminfacebook',$res);
            }else{
                cookie('adminfacebook','发生未知错误');
            }
            return array('success'=>true);
        }

    }
}
